import { createRouter, createWebHistory } from 'vue-router'

// 添加路由调试日志
const routeDebug = (to, from, next) => {
  console.log('===== 路由调试 =====')
  console.log('从:', from.path)
  console.log('到:', to.path)
  console.log('路由配置:', to)
  next()
}

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/dashboard/index.vue'),
    meta: { title: '工作台' }
  },
  {
    path: '/statistics',
    name: 'Statistics',
    component: () => import('@/views/statistics/index.vue'),
    meta: { title: '数据统计' }
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('@/views/orders/index.vue'),
    meta: { title: '订单管理' },
    beforeEnter: (to, from, next) => {
      console.log('尝试进入订单管理页面', to.path)
      console.log('订单组件:', typeof import('@/views/orders/index.vue'))
      next()
    }
  },
  // 添加额外的可测试路由
  {
    path: '/orders-test',
    name: 'OrdersTest',
    component: () => import('@/views/orders/index.vue'),
    meta: { title: '订单管理测试' }
  },
  {
    path: '/setmeal',
    name: 'Setmeal',
    component: () => import('@/views/setmeal/index.vue'),
    meta: { title: '套餐管理' }
  },
  {
    path: '/setmeal/add',
    name: 'SetmealAdd',
    component: () => import('@/views/setmeal/edit.vue'),
    meta: { title: '添加套餐' }
  },
  {
    path: '/setmeal/edit/:id',
    name: 'SetmealEdit',
    component: () => import('@/views/setmeal/edit.vue'),
    meta: { title: '编辑套餐' }
  },
  {
    path: '/dish',
    name: 'Dish',
    component: () => import('@/views/dish/index.vue'),
    meta: { title: '菜品管理' }
  },
  {
    path: '/dish/add',
    name: 'DishAdd',
    component: () => import('@/views/dish/edit.vue'),
    meta: { title: '添加菜品' }
  },
  {
    path: '/dish/edit/:id',
    name: 'DishEdit',
    component: () => import('@/views/dish/edit.vue'),
    meta: { title: '编辑菜品' }
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import('@/views/category/index.vue'),
    meta: { title: '分类管理' }
  },
  {
    path: '/employee',
    name: 'employee',
    component: () => import('../views/employee/index.vue'),
    meta: { title: '员工管理' }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/employee/profile.vue'),
    meta: { title: '个人信息' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  console.log('路由守卫: 从', from.path, '到', to.path)
  document.title = to.meta.title ? `${to.meta.title} - 餐厅管理系统` : '餐厅管理系统'
  
  // 检查是否需要登录
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    console.log('路由守卫: 无token，重定向到登录页')
    next('/login')
  } else {
    console.log('路由守卫: 允许通过')
    next()
  }
})

export default router 